import subprocess
from functools import partial
subprocess.Popen = partial(subprocess.Popen, encoding="utf-8")

import requests
import time
import execjs

headers = {
    "Connection": "keep-alive",
    "Pragma": "no-cache",
    "Cache-Control": "no-cache",

    "Accept": "application/json, text/plain, */*",
    "Content-Type": "application/x-www-form-urlencoded",
    "sec-ch-ua-mobile": "?0",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Core/1.94.253.400 QQBrowser/12.6.5678.400",

    "Origin": "https://fanyi.youdao.com",
    "Sec-Fetch-Site": "same-site",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Dest": "empty",
    "Referer": "https://fanyi.youdao.com/",
    "Accept-Language": "zh-CN,zh;q=0.9"
}

cookies = {
    "OUTFOX_SEARCH_USER_ID": "1366935620@240e:3b6:30f5:1fb0:cddf:fe47:396d:d8",
    "OUTFOX_SEARCH_USER_ID_NCOO": "1079190392.6667542",
    "DICT_DOCTRANS_SESSION_ID": "YTAwMTQ2NzgtMzQzMC00MTk2LTllN2EtMmM1NjU5ZWQ5ZWM1",
    "_uetsid": "535e66908ac211ef8f09d9fd65e09f0f",
    "_uetvid": "535e71408ac211ef90ad8b4dd48f0527"
}
secretKey = 'fsdsogkndfokasodnaso'
query = input('输入要翻译的内容:')
url = "https://dict.youdao.com/webtranslate"
with open('yd.js', 'r', encoding='utf-8') as f:
    ctx = execjs.compile(f.read())
mil_ts = int(time.time() * 1000) # 与js的时间戳不一样
sign = ctx.call('get_sign', mil_ts, secretKey)
data = {
    "i": query,
    "from": "auto",
    "to": "",
    "useTerm": "false",
    "domain": "0",
    "dictResult": "true",
    "keyid": "webfanyi",
    "sign": sign,
    "client": "fanyideskweb",
    "product": "webfanyi",
    "appVersion": "1.0.0",
    "vendor": "web",
    'pointParam': 'client,mysticTime,product',
    "mysticTime": mil_ts,
    "keyfrom": "fanyi.web",
    "mid": "1",
    "screen": "1",
    "model": "1",
    "network": "wifi",
    "abtest": "0",
    "yduuid": "abcdefg"
}

response = requests.post(url, headers=headers, cookies=cookies, data=data)

# 处理两个参数 正确访问到接口
key = "ydsecret://query/key/B*RGygVywfNBwpmBaZg*WT7SIOUP2T0C9WHMZN39j^DAdaZhAnxvGcCY6VYFwnHl"
iv = "ydsecret://query/iv/C@lZe2YzHtZ2CYgaXKSVfsb7Y4QWHjITPPZ0nQp87fBeJ!Iv6v^6fvi2WN@bYpJ4"
#  对响应的json数据进行解密
plain_text = ctx.call('decrypt_youdao', response.text, key, iv)
print(plain_text)

